package com.cater.talents.controller;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.cater.annotation.SystemControllerLog;
import com.cater.common.PageResult;
import com.cater.common.UserContext;
import com.cater.project.entity.DemandCommunicate;
import com.cater.project.entity.DemandEnterprise;
import com.cater.project.service.DemandCommunicateServiceImpl;
import com.cater.project.service.DemandEnterpriseServiceImpl;
import com.cater.query.CommonQuery;
import com.cater.sys.entity.Area;
import com.cater.sys.entity.Dictionarydata;
import com.cater.sys.entity.User;
import com.cater.sys.service.UserService;
import com.cater.sys.service.impl.AreaServiceImpl;
import com.cater.sys.service.impl.CompanyServiceImpl;
import com.cater.sys.service.impl.DictionarydataServiceImpl;
import com.cater.talents.entity.EduExperience;
import com.cater.talents.entity.Resume;
import com.cater.talents.entity.ResumeProject;
import com.cater.talents.entity.ResumeRelationship;
import com.cater.talents.entity.TalentsRecommend;
import com.cater.talents.entity.TbCertificate;
import com.cater.talents.entity.UserResume;
import com.cater.talents.entity.WorkExperience;
import com.cater.talents.service.EduExperienceServiceImpl;
import com.cater.talents.service.ResumeProjectServiceImpl;
import com.cater.talents.service.ResumeRelationshipServiceImpl;
import com.cater.talents.service.ResumeServiceImpl;
import com.cater.talents.service.TalentsRecommendServiceImpl;
import com.cater.talents.service.TbCertificateServiceImpl;
import com.cater.talents.service.UserResumeServiceImpl;
import com.cater.talents.service.WorkExperienceServiceImpl;
import com.cater.talents.utils.ReadWordUitl;
import com.cater.talents.utils.RegexUtils;
import com.cater.utils.StringUitl;

/**
 * @author yong
 * @Date 2018年3月22日-下午9:54:50
 * @简历管理控制层
 */
@Controller
@RequestMapping("/resume")
public class ResumeController {
	@Autowired
	private ResumeServiceImpl service;
	@Autowired
	private WorkExperienceServiceImpl experienceService;// 工作经验
	@Autowired
	private CompanyServiceImpl companyService;// 公司
	@Autowired
	private EduExperienceServiceImpl eduExperienceService;// 教育及培训
	@Autowired
	private AreaServiceImpl areaService;// 区域
	@Autowired
	private DemandCommunicateServiceImpl communicateService;// 沟通记录
	@Autowired
	private UserService userService;// 用户
	@Autowired
	private UserResumeServiceImpl userResumeService;// 用户简历关联表
	@Autowired
	private DemandEnterpriseServiceImpl demandEnterpriseService;// 企业需求
	@Autowired
	private ResumeProjectServiceImpl resumeProjectService;// 简历项目关联
	@Autowired
	private DictionarydataServiceImpl dictService;// 字典
	@Autowired
	private TalentsRecommendServiceImpl recommendService;// 推荐
	@Autowired
	private TbCertificateServiceImpl certificateService;// 资格证书
	@Autowired
	private ResumeRelationshipServiceImpl resumeRelationshipService;

	/**
	 * @简历管理列表视图
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model, String name, String phone) {
		List<User> users = userService.getAll();
		model.addAttribute("users", users);
		if (StringUtils.isNotEmpty(name)) {
			model.addAttribute("name", name);
		}
		if (StringUtils.isNotEmpty(phone)) {
			model.addAttribute("phone", phone);
		}
		return "talents/resume/list";
	}

	/**
	 * @简历管理数据分页
	 * @param query
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("listData")
	@ResponseBody
	@SystemControllerLog(description = "查询简历分页数据")
	public PageResult<Resume> listData(CommonQuery query, HttpServletRequest request) throws ParseException {
		PageResult<Resume> result = service.findPageResult(query);
		Integer userId = UserContext.getId();
		Integer roleId = UserContext.getIsadminType();
		List<UserResume> userResumes = userResumeService.getListByUserId(userId);
		for (Resume resume : result.getRows()) {
			String resumeId = resume.getId();
			Integer createUserId = resume.getCreateUserId();
			String cellphone = resume.getCellphone();
			String lifephone = resume.getLifephone();
			String temp = "";
			if (StringUtils.isNotEmpty(cellphone)) {
				temp += cellphone;
			} else if (StringUtils.isNotEmpty(lifephone)) {
				temp += lifephone;
			} else {
				temp = "暂无";
			}
			resume.setPhoneview(temp);
			String birthdate = resume.getBirthdate();
			if (StringUtils.isNotEmpty(birthdate)) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Date bithday = format.parse(birthdate);
				int age = StringUitl.getAgeByBirth(bithday);
				resume.setAge(age + "岁");
			} else {
				resume.setAge("无");
			}
			resume.setIsable(0);
			if (roleId == 4) {
				if (userResumes.size() > 0) {
					for (UserResume userResume : userResumes) {
						String uResumeId = userResume.getResumeId();
						if (!resumeId.equals(uResumeId) && !createUserId.equals(userId)) {
							if (!temp.equals("暂无")) {
								resume.setPhoneview(temp.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
							}
							resume.setIsable(1);
						}
					}
				}
			}
		}
		return result;
	}

	/**
	 * 
	 * @Description:添加视图
	 * @param model
	 * @param query
	 * @return String
	 * @time:2018年4月15日 上午11:00:32
	 */
	@RequestMapping(value = "addView")
	@RequiresPermissions("resume:add")
	public String addView(Model model, CommonQuery query) {
		model.addAttribute("id", UUID.randomUUID().toString().replaceAll("-", ""));
		/*
		 * List<Company> companies = companyService.getAll();
		 * model.addAttribute("company", companies);
		 */
		return "talents/resume/add_resume";
	}

	@RequestMapping(value = "add")
	@RequiresPermissions("resume:add")
	@ResponseBody
	@SystemControllerLog(description = "添加简历")
	public JSONObject add(Resume t, HttpServletRequest request, CommonQuery query) {
		JSONObject json = new JSONObject();
		try {
			String id = service.saves(t);
			if (StringUtils.isNotEmpty(id)) {
				json.put("code", 200);
				json.put("message", "success");
			} else {
				json.put("code", 999);
				json.put("message", "fail");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "fail");
		}
		return json;
	}

	/**
	 * 修改视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "editView")
	@RequiresPermissions("resume:edit")
	public String editView(String id, Model model, CommonQuery query, HttpServletRequest request) {
		Resume t = service.getById(id);
		String locationA = t.getLocation();
		if (StringUtils.isNotEmpty(locationA)) {
			Area locationarea = this.areaService.getById(locationA);
			t.setLocationArea(locationarea);
		}
		String householdA = t.getHousehold();
		if (StringUtils.isNotEmpty(householdA)) {
			Area household_area = this.areaService.getById(householdA);
			t.setHouseholdArea(household_area);
		}
		String nativesA = t.getNatives();
		if (StringUtils.isNotEmpty(nativesA)) {
			Area natives_area = this.areaService.getById(nativesA);
			t.setNativeArea(natives_area);
		}
		model.addAttribute("resume", t);
		String tops = request.getParameter("tops");
		if (StringUtils.isNotEmpty(tops)) {
			model.addAttribute("tops", tops);
		}
		return "talents/resume/update";
	}

	/**
	 * 修改操作
	 * 
	 * @param t
	 * @return
	 */
	@RequestMapping(value = "update")
	@RequiresPermissions("resume:edit")
	@ResponseBody
	@SystemControllerLog(description = "修改简历")
	public JSONObject update(Resume t, HttpServletRequest request, CommonQuery query) {
		JSONObject json = new JSONObject();
		try {
			Resume tresume = service.getById(t.getId());
			String tlocation = t.getLocation();// 目前所在城市
			String thousehold = t.getHousehold();// 户口所在地
			String tnatives = t.getNatives();// 籍贯
			if (StringUtils.isEmpty(tlocation)) {
				t.setLocation(tresume.getLocation());
			}
			if (StringUtils.isEmpty(thousehold)) {
				t.setHousehold(tresume.getHousehold());
			}
			if (StringUtils.isEmpty(tnatives)) {
				t.setNatives(tresume.getNatives());
			}
			service.update(t);
			json.put("code", 200);
			json.put("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "修改失败");
		}
		return json;
	}

	/**
	 * 删除操作
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("resume:delete")
	@SystemControllerLog(description = "删除简历")
	public JSONObject delete(String id) {
		JSONObject json = new JSONObject();
		try {
			service.delete(id);
			json.put("code", 200);
			json.put("message", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "删除失败");
		}
		return json;
	}

	@ResponseBody
	@RequestMapping("/upload")
	public JSONObject Upload(HttpServletRequest request, Model model, CommonQuery query) {
		JSONObject json = new JSONObject();
		String path = request.getServletContext().getRealPath("/static/upload/doc/");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		try {
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			file.transferTo(new File(path + fileName));
			String tString = ReadWordUitl.readDocx(path + fileName);
			Resume resume = new Resume();
			List<String> listtemp = new ArrayList<String>();
			for (String string : tString.split("\n")) {
				if (StringUtils.isNotEmpty(string) && !string.equals("\t")) {
					listtemp.add(string);
				}
			}
			for (int m = 0; m < listtemp.size(); m++) {
				System.out.println(listtemp.get(m));
				// 在职状态
				if (resume.getIschance() == null) {
					if (listtemp.get(0).indexOf("在职") >= 0) {
						resume.setIschance(1);
					} else if (listtemp.get(0).indexOf("离职") >= 0) {
						resume.setIschance(2);
					} else {
						resume.setIschance(3);
					}
				}
				if (m == 3) {
					// 姓名
					resume.setTrueName(RegexUtils.getName(listtemp.get(3)));
					// 性别
					if (listtemp.get(3).indexOf("男") >= 0) {
						resume.setSex(1);
					} else {
						resume.setSex(2);
					}
				}
				if (m == 4) {
					// 手机号码
					String phone = RegexUtils.getName(listtemp.get(4));
					for (String t_phone : phone.split("：")) {
						phone = t_phone;
					}
					if (StringUtils.isNotEmpty(phone)) {
						resume.setCellphone(phone);
						resume.setWechat(phone);
					}
				}
				if (m == 5) {
					// 邮箱
					String email = RegexUtils.getName(listtemp.get(5));
					Boolean isemail = RegexUtils.getEmail(email);
					if (isemail) {
						resume.setEmail(email);
					}
					// 教育程度
					String education = RegexUtils.getLastName(listtemp.get(5));
					resume.setEducation(education);
				}
				if (m == 6) {
					// 婚姻状况
					if (listtemp.get(6).indexOf("已婚") >= 0) {
						resume.setIschance(1);
					} else if (listtemp.get(0).indexOf("未婚") >= 0) {
						resume.setIschance(2);
					} else {
						resume.setIschance(3);
					}
				}
				if (m == 7) {
					// 所在地
					String location = RegexUtils.getName(listtemp.get(7));
					if (StringUtils.isNotEmpty(location)) {
						query.setName(location);
						Area locationArea = this.areaService.getByName(query);
						resume.setLocationArea(locationArea);
					}
				}
				if (m == 9) {
					// 公司名称
					String company = RegexUtils.getLastName(listtemp.get(9));
				}
				if (m == 10) {
					// 职位
					String position = RegexUtils.getName(listtemp.get(10));
					// 年薪
					String expectSalarystart = RegexUtils.getLastName(listtemp.get(10));
				}
				if (m == 14) {
					// 期望城市
					String expectedCity = RegexUtils.getName(listtemp.get(14));
					if (StringUtils.isNotEmpty(expectedCity)) {
						query.setName(expectedCity);
						Area expectedArea = this.areaService.getByName(query);
						resume.setExpectedCity(String.valueOf(expectedArea.getId()));
						resume.setExpectedCityNames(expectedArea.getTitle());
					}
				}
			}
			json.put("datas", resume);
			json.put("code", 200);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
		}
		return json;
	}

	/**
	 * 查看视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "detailView")
	@RequiresPermissions("resume:detail")
	public String detailView(String id, Model model, CommonQuery query) {
		Resume t = service.getById(id);
		Integer userId = UserContext.getId();
		Integer roleId = UserContext.getIsadminType();
		List<UserResume> userResumes = userResumeService.getListByUserId(userId);
		String locationA = t.getLocation();
		if (StringUtils.isNotEmpty(locationA)) {
			Area locationarea = this.areaService.getById(locationA);
			t.setLocationArea(locationarea);
		}
		String householdA = t.getHousehold();
		if (StringUtils.isNotEmpty(householdA)) {
			Area household_area = this.areaService.getById(householdA);
			t.setHouseholdArea(household_area);
		}
		String nativesA = t.getNatives();
		if (StringUtils.isNotEmpty(nativesA)) {
			Area natives_area = this.areaService.getById(nativesA);
			t.setNativeArea(natives_area);
		}
		String cellphone = t.getCellphone();
		String lifephone = t.getLifephone();
		String temp = "";
		if (StringUtils.isNotEmpty(cellphone)) {
			temp += cellphone;
		} else if (StringUtils.isNotEmpty(lifephone)) {
			temp += lifephone;
		} else {
			temp = "暂无";
		}
		if (roleId == 4) {
			if (userResumes.size() > 0) {
				for (UserResume userResume : userResumes) {
					if (!id.equals(userResume.getResumeId()) && !userId.equals(t.getCreateUserId())) {
						if (!temp.equals("暂无")) {
							temp = temp.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
						}
						String email = t.getEmail();
						if (StringUtils.isNotEmpty(email)) {
							t.setEmail(email.replaceAll("(\\w?)(\\w+)(\\w)(@\\w+\\.[a-z]+(\\.[a-z]+)?)", "$1****$3$4"));
						}
						t.setWechat("***");
						t.setQq("***");
						t.setLinkedin("***");
					}
				}
			}
		}
		t.setPhoneview(temp);
		model.addAttribute("resume", t);
		query.setTalentsId(id);
		query.setType("");
		List<WorkExperience> workExperiences = experienceService.getListByTalentsId(query);
		model.addAttribute("workExperiences", workExperiences);
		model.addAttribute("workcount", workExperiences.size());
		query.setType("1");
		List<EduExperience> schools = eduExperienceService.getListByTalentsId(query);
		model.addAttribute("schools", schools);
		model.addAttribute("schoolcount", schools.size());
		query.setType("2");
		List<EduExperience> trains = eduExperienceService.getListByTalentsId(query);
		model.addAttribute("trains", trains);
		model.addAttribute("traincount", trains.size());
		List<DemandCommunicate> communicates = communicateService.getListBytelentsId(query);
		model.addAttribute("communicates", communicates);
		model.addAttribute("communicatecount", communicates.size());
		List<TalentsRecommend> recommends = recommendService.getByTalentsId(id);
		model.addAttribute("recommends", recommends);
		model.addAttribute("recommendcount", recommends.size());
		List<TbCertificate> certificates = certificateService.getByTatentsId(id);
		model.addAttribute("certificates", certificates);
		model.addAttribute("certificatecount", certificates.size());
		List<ResumeRelationship> relationships = resumeRelationshipService.getListBy(id);
		model.addAttribute("relationships", relationships);
		model.addAttribute("relationshipscount", relationships.size());
		return "talents/resume/detail";
	}

	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping("/report") public JSONObject Report(String id, String posts,
	 * String reason, HttpServletRequest request, CommonQuery query) { JSONObject
	 * json = new JSONObject(); String filename = new String(); SimpleDateFormat
	 * formatter = new SimpleDateFormat("yyyy年MM月dd日"); String dateString =
	 * formatter.format(new Date()); try { Resume resume = service.getById(id);
	 * query.setTalentsId(id); List<WorkExperience> workExperiences =
	 * experienceService.getListByTalentsId(query);
	 * resume.setWorkExperiences(workExperiences); query.setType("1");
	 * List<EduExperience> eduExperiences =
	 * eduExperienceService.getListByTalentsId(query);
	 * resume.setEduExperiences(eduExperiences); query.setType("2");
	 * List<EduExperience> trainExperiences =
	 * eduExperienceService.getListByTalentsId(query);
	 * 
	 * resume.setTrainExperiences(trainExperiences); Map<String, Object> map = new
	 * HashMap<>(); map.put("doc", resume); map.put("posts", posts);
	 * map.put("reason", reason); map.put("datenow", dateString); String locationA =
	 * resume.getLocation(); if (StringUtils.isNotEmpty(locationA)) { Area
	 * locationarea = this.areaService.getById(locationA); map.put("location",
	 * locationarea.getTitle()); } String householdA = resume.getHousehold(); if
	 * (StringUtils.isNotEmpty(householdA)) { Area household_area =
	 * this.areaService.getById(householdA); map.put("household",
	 * household_area.getTitle()); } String nativesA = resume.getNatives(); if
	 * (StringUtils.isNotEmpty(nativesA)) { Area natives_area =
	 * this.areaService.getById(nativesA); map.put("natives",
	 * natives_area.getTitle()); } FreemarkerUtil freemarker = new FreemarkerUtil();
	 * freemarker.fprint("recommend_report.ftl", map, filename + ".docx", request);
	 * json.put("code", 200); json.put("doc", "/static/report/" + filename +
	 * ".docx"); json.put("message", "推荐报告生成成功"); } catch (Exception e) {
	 * json.put("code", 999); json.put("message", "推荐报告生成失败"); } return json;
	 * 
	 * }
	 */
	/**
	 * 
	 * @Description:姓名去重查询
	 * @param query
	 * @return JSONObject
	 * @time:2018年7月17日 上午7:21:00
	 */
	@ResponseBody
	@RequestMapping("isableName")
	public JSONObject IsableName(CommonQuery query) {
		JSONObject json = new JSONObject();
		try {
			List<Resume> resumes = service.getByName(query);
			if (resumes.size() > 0) {
				json.put("code", 400);
				json.put("message", "该信息已存在，请查证");
			} else {
				json.put("code", 200);
				json.put("message", "该信息为首次添加");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping("/chooseResume")
	public String chooseResume(String trueName, String position, Model model, CommonQuery query) {
		if (StringUtils.isEmpty(trueName)) {
			trueName = "";
		}
		if (StringUtils.isEmpty(position)) {
			position = "";
		}
		model.addAttribute("trueName", trueName);
		model.addAttribute("position", position);
		return "talents/resume/choose_resume";
	}

	/**
	 * 授权简历视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "authView")
	@RequiresPermissions("resume:auth")
	public String authView(String ids, Model model, CommonQuery query) {
		return "talents/userResume/add";
	}

	/**
	 * 加入项目视图
	 * 
	 * @param id
	 * @param model
	 * @param query
	 * @return
	 */
	@RequestMapping(value = "addProjectView")
	@RequiresPermissions("resume:add")
	public String addProjectView(String id, Model model, CommonQuery query) {
		model.addAttribute("resumeId", id);
		List<DemandEnterprise> demandEnterprises = demandEnterpriseService.getAll();
		model.addAttribute("demandEnterprises", demandEnterprises);
		return "talents/resume/add_project";
	}

	/**
	 * 加入项目操作
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "addProject")
	@RequiresPermissions("resume:add")
	@ResponseBody
	@SystemControllerLog(description = "加入项目")
	public JSONObject addProject(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			String resumeId = request.getParameter("resumeId");
			String projectId = request.getParameter("projectId");
			Integer count = resumeProjectService.getCount(resumeId, projectId);
			if (count > 0) {
				json.put("code", 400);
				json.put("message", "请勿重复操作！");
			} else {
				ResumeProject rProject = new ResumeProject();
				rProject.setResumeId(resumeId);
				rProject.setProjectId(projectId);
				rProject.setStatus("5");
				resumeProjectService.saves(rProject);
				json.put("code", 200);
				json.put("message", "加入项目成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "加入项目失败");
		}
		return json;
	}

	/**
	 * @简历管理列表视图
	 * @return
	 */
	@RequestMapping("/listForProject")
	public String listForProject(String projectId, String companyId, Model model) {
		model.addAttribute("projectId", projectId);
		model.addAttribute("companyId", companyId);
		return "talents/resume/list_project";
	}

	@RequestMapping("listProjectData")
	@ResponseBody
	@SystemControllerLog(description = "查询项目简历分页数据")
	public List<Resume> listProjectData(CommonQuery query, HttpServletRequest request) {
		String projectId = request.getParameter("projectId");
		List<Resume> list = new ArrayList<Resume>();
		Dictionarydata dictStatus = null;
		if (StringUtils.isNotEmpty(projectId)) {
			List<ResumeProject> rProjects = resumeProjectService.getByProjectId(projectId);
			for (ResumeProject tProject : rProjects) {
				Resume resume = service.getById(tProject.getResumeId());
				String status = tProject.getStatus();
				if (StringUtils.isNotEmpty(status)) {
					dictStatus = new Dictionarydata();
					dictStatus = dictService.getByTypeValue(status, "resume_status");
					resume.setDictStatus(dictStatus.getValueName());
				}
				String cellphone = resume.getCellphone();
				String lifephone = resume.getLifephone();
				String temp = "";
				if (StringUtils.isNotEmpty(cellphone)) {
					temp += cellphone;
				} else if (StringUtils.isNotEmpty(lifephone)) {
					temp += lifephone;
				} else {
					temp = "暂无";
				}
				resume.setPhoneview(temp);
				list.add(resume);
			}
		}
		return list;
	}

	@ResponseBody
	@RequestMapping("getByPhone")
	public JSONObject getByPhone(String phone, CommonQuery query) {
		JSONObject json = new JSONObject();
		try {
			query.setPhone(phone);
			List<Resume> resumes = service.getByName(query);
			if (resumes.size() > 0) {
				json.put("resumes", resumes.get(0));
				json.put("code", 200);
				json.put("message", "数据获取成功");
			} else {
				json.put("code", 400);
				json.put("message", "暂无数据");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}
}
